package org.fxml.commands {
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;

	/**
	 * @author jordandoczy
	 */
	public class Command extends EventDispatcher implements ICommand {
		
		protected var _delegate:Function;
		protected var _errorEvent:String;
		protected var _event:String;
		protected var _params:Array;
		protected var _target:IEventDispatcher;
		
		public function Command(delegate:Function=null, target:IEventDispatcher=null, event:String=null, params:Array=null, errorEvent:String=null){
			_delegate = delegate;
			_target = target;
			_event = event;
			_errorEvent = errorEvent;
			_params = params;
		}
		
		public function execute():void{
			if(_target != null && _event != null){
				 _target.addEventListener(_event, onOperationComplete, false, 0, true);
				 if(_errorEvent) _target.addEventListener(_errorEvent, onOperationComplete, false, 0, true);
			}
			
			_delegate.apply(null, _params);
			
			if(_target == null || _event == null) onOperationComplete();
		}
		
		protected function onOperationComplete(e:Event=null):void{
			if(_target != null && _event != null) _target.removeEventListener(_event, onOperationComplete);
			dispatchEvent(new Event(Event.COMPLETE)); 
		}
	}
}
